package com.voicechat.firstmet.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.adapter.ShareGirlsOrderAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PayResult;
import com.voicechat.firstmet.bean.ShareGirlsOrderBean;
import com.voicechat.firstmet.dialog.AlertDialog;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.AlipaySerivice;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: BlindDateOrderFragment
 * @Description: 隐约下单订单页面    item:   item_blind_date_order
 * @Author: ljp
 * @CreateDate: 2019/1/19 11:31
 * @Version: 1.0
 */
public class BlindDatePlaceOrderFragment extends BaseFragment {
    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.default_image_view)
    ImageView defaultImageView;
    @BindView(R.id.default_text_view)
    TextView defaultTextView;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;

    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    private List<ShareGirlsOrderBean.PageBean.ListBean> listBeans;
    private int page;
    private ShareGirlsOrderAdapter shareGirlsOrderAdapter;
    private String TAG = "BlindDatePlaceOrderFragment";
    private AlertDialog myDialog;
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        try {
                            JSONObject jsonObject = new JSONObject(resultInfo);
                            if (jsonObject.has("alipay_trade_app_pay_response")) {
                                JSONObject alipay_trade_app_pay_response = jsonObject.getJSONObject("alipay_trade_app_pay_response");
                                if (alipay_trade_app_pay_response.has("out_trade_no")) {
                                    String out_trade_no = alipay_trade_app_pay_response.getString("out_trade_no");
                                    judeRecharge(out_trade_no);//判断是否购买成功
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        textvSure.setEnabled(true);
                        toast_MakeText("支付已经取消");
                    } else {
                        textvSure.setEnabled(true);
                        toast_MakeText("支付失败,请重试");
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //showPopu();//弹出购买失败框
                    }
                    break;
                }
            }
        }
    };
    /**
     * @return
     * @method
     * @description 购买结果的判断
     * @date: 2019/1/10 10:09
     * @author: ljp
     */
    private void judeRecharge(String orderStr) {
        AlipaySerivice.judeAlipay(orderStr).subscribe(result -> {
            //textvSure.setEnabled(true);
            Log.i(TAG, "judeRecharge: -----" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {//支付成功

                page = 1;
                initHttp();
            } else {
                textvSure.setEnabled(true);
                toast_MakeText(result.getMsg());
            // showPopu();//弹出购买失败框
            }
        }, throwable -> {
            textvSure.setEnabled(true);
            // tvPay.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
            // showPopu();//弹出购买失败框
            Log.i(TAG, "judeRecharge: ---------" + throwable.toString());
        });
    }

    public static BlindDatePlaceOrderFragment newInstance() {
        Bundle args = new Bundle();
        BlindDatePlaceOrderFragment fragment = new BlindDatePlaceOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int loadLayout() {
        return R.layout.fragment_blind_order;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }

    TextView textvCancel;
    TextView textvSure;

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2019/1/23 16:06
     * @author: ljp
     */
    private void initView() {
        myDialog = new AlertDialog(activity).builder();
        listBeans = new ArrayList<>();
        smartRefresh.autoRefresh();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                initHttp();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttp();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        shareGirlsOrderAdapter = new ShareGirlsOrderAdapter(context, listBeans, R.layout.item_blind_date_order, "place");
        recyclerList.setLayoutManager(new LinearLayoutManager(context));
        recyclerList.setAdapter(shareGirlsOrderAdapter);
        shareGirlsOrderAdapter.setOrderOnClick(new ShareGirlsOrderAdapter.OrderOnClick() {
            @Override
            public void setPlaceOrderOnClick(ShareGirlsOrderBean.PageBean.ListBean listBean,
                                             int flag, TextView tvCancel, TextView tvSure) {
                Log.i(TAG, "setPlaceOrderOnClick: ------flag------" + flag);
                switch (flag) { //下单者 //1取消订单   2完成订单   3申请退款 4去支付
                    case 1:
                        textvCancel = tvCancel;
                        textvSure = tvSure;
                        textvCancel.setEnabled(false);
                        if(listBean.getComplete() == 2 && listBean.getPaySign() == 1){//未支付取消
                            myDialog.setGone().setMsg(getResources().getString(R.string.place_cancel)).
                                    setNegativeButton("再想想", R.color.colorAccent, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            textvCancel.setEnabled(true);
                                        }
                                    }).
                                    setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            FaintService.completeCancelOrder(token, deviceInfo, listBean.getId(), 3, listBean.getRmb()).subscribe(result -> {
                                                Log.i(TAG, "completeCancelOrder: ---13---"+result.toString());
                                                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                                                        listBean.setComplete(3);
                                                        shareGirlsOrderAdapter.notifyDataSetChanged();
                                                } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                                                    textvCancel.setEnabled(true);
                                                    Utils.setToken(context);
                                                } else {
                                                    textvCancel.setEnabled(true);
                                                    toast_MakeText(result.getMsg());
                                                }
                                                // toast_MakeText(result.getMsg());
                                            }, throwable -> {
                                                textvCancel.setEnabled(true);
                                                Log.i(TAG, "completeCancelOrder: ----------" + throwable.toString());
                                            });
                                        }
                                    }).show();
                        }else {//已经支付取消
                            completeCancelOrder(listBean, 1);
                        }
                        break;
                    case 2:
                        completeCancelOrder(listBean, 2);
                        break;
                    case 3:
                        completeCancelOrder(listBean, 3);
                        break;
                    case 4:
                        //去支付
                        textvSure = tvSure;
                        textvSure.setEnabled(false);
                        getPayOrder(listBean);
                        break;
                }
            }

            @Override
            public void setReceiveOrderOnClick(ShareGirlsOrderBean.PageBean.ListBean listBean, int flag, TextView textViewCancel, TextView tvSure) {
            }

            @Override
            public void setPerson(ShareGirlsOrderBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", listBean.getUserId());
                context.startActivity(intent);
            }
        });
    }

    /**
     * @return
     * @method
     * @description 请求订单号
     * @date: 2019/1/21 17:48
     * @author: ljp
     */
    public void getPayOrder(ShareGirlsOrderBean.PageBean.ListBean listBean) {
        AlipaySerivice.againPayOrder(listBean.getId(), listBean.getRmb()).subscribe(alipayBean -> {
            if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Log.i(TAG, "getPayOrder: -----getOrderName----" + alipayBean.getMap().getOrderName());
                //judeRecharge(alipayBean.getMap().getOrderName());
                setAlipay(alipayBean.getMap().getOrderStr());
            } else if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                textvSure.setEnabled(true);
                toast_MakeText(alipayBean.getMsg());
            }
        }, throwable -> {
            textvSure.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "toPay: ---------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 支付宝支付
     * @date: 2019/1/10 10:44
     * @author: ljp
     */
    private void setAlipay(String orderInfo) {
        Log.i(TAG, "setAlipay: -------orderInfo-----" + orderInfo);
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i(TAG, "run: -----------" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * @return
     * @method
     * @description 取消/完成订单
     * @date: 2019/1/26 11:24
     * @author: ljp
     */
    private void completeCancelOrder(ShareGirlsOrderBean.PageBean.ListBean listBean, int i) {
        if (i == 1 || i == 3) {//1取消订单   2完成订单
            FaintService.completeCancelOrder(token, deviceInfo, listBean.getId(), i == 1 ? 3 : 6, listBean.getRmb()).subscribe(result -> {
                Log.i(TAG, "completeCancelOrder: ---13---"+result.toString());
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    if (i == 1) {
                        myDialog.setGone().setMsg(getResources().getString(R.string.place_cancel)).
                                setNegativeButton("再想想", R.color.colorAccent, null).
                                setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        listBean.setComplete(7);
                                        shareGirlsOrderAdapter.notifyDataSetChanged();
                                    }
                                }).show();
                        textvCancel.setEnabled(true);
                    } else {
                        toast_MakeText(getResources().getString(R.string.receive_accept_refund));
                        listBean.setComplete(3);
                        shareGirlsOrderAdapter.notifyDataSetChanged();
                    }
                } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    textvCancel.setEnabled(true);
                    Utils.setToken(context);
                } else {
                    textvCancel.setEnabled(true);
                    toast_MakeText(result.getMsg());
                }
                // toast_MakeText(result.getMsg());
            }, throwable -> {
                textvCancel.setEnabled(true);
                Log.i(TAG, "completeCancelOrder: ----------" + throwable.toString());
            });
        } else if(i == 2){
            FaintService.completeCancelOrder(token, deviceInfo, listBean.getId(), 1, listBean.getRmb()).subscribe(result -> {
                Log.i(TAG, "completeCancelOrder: ----------" + result.toString());
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    toast_MakeText(result.getMsg());
                    listBean.setComplete(1);
                    shareGirlsOrderAdapter.notifyDataSetChanged();
                } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    textvSure.setEnabled(true);
                    Utils.setToken(context);
                } else {
                    textvSure.setEnabled(true);
                    toast_MakeText(result.getMsg());
                }
            }, throwable -> {
                textvSure.setEnabled(true);
                Log.i(TAG, "completeCancelOrder: ----------" + throwable.toString());
            });
        }

    }

    /**
     * @return
     * @method
     * @description 网络请求
     * @date: 2019/1/23 16:25
     * @author: ljp
     */
    private void initHttp() {
        FaintService.selectShareGirlsPlaceOrder(token, deviceInfo, mySeleInfo.getId()).subscribe(shareGirlsOrderBean -> {
            if (shareGirlsOrderBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = shareGirlsOrderBean.getPage().getCount() / shareGirlsOrderBean.getPage().getPageSize() +
                        (shareGirlsOrderBean.getPage().getCount() % shareGirlsOrderBean.getPage().getPageSize() == 0 ? 0 : 1);
                //Log.i(TAG, "initHttp: ---shareGirlsOrderBean----"+shareGirlsOrderBean.getPage().getList().size());
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        listBeans.clear();
                        smartRefresh.finishRefresh();
                    }
                    Log.i(TAG, "initHttp: ------getList------"+shareGirlsOrderBean.getPage().getCount());
                    if(shareGirlsOrderBean.getPage().getList() != null) {
                        linearLayout.setVisibility(View.GONE);
                        listBeans.addAll(shareGirlsOrderBean.getPage().getList());
                        shareGirlsOrderAdapter.notifyDataSetChanged();
                        smartRefresh.setVisibility(View.VISIBLE);
                        smartRefresh.finishLoadMore();
                    }else {
                        smartRefresh.setVisibility(View.GONE);
                        linearLayout.setVisibility(View.VISIBLE);
                    }
                   /* if (shareGirlsOrderBean.getPage().getList() != null) {
                        listBeans.addAll(shareGirlsOrderBean.getPage().getList());
                        shareGirlsOrderAdapter.notifyDataSetChanged();
                        // smartRefresh.setVisibility(View.VISIBLE);
                    } else {
                        //  linearLayout.setVisibility(View.VISIBLE);
                    }*/
                    smartRefresh.finishLoadMore();
                }
            } else if (shareGirlsOrderBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(shareGirlsOrderBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "initHttp: ---------" + throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }
}
